package com.ruoyi.web.controller.app;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.nongjt.domain.Login;
import com.ruoyi.nongjt.domain.LoginResult;
import com.ruoyi.nongjt.domain.NjtUserRegister;
import com.ruoyi.nongjt.service.ILoginService;
import com.ruoyi.nongjt.service.INjtUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录验证Controller(小程序)
 *
 * @author ruoyi
 * @date 2024-09-27
 */
@RestController
@RequestMapping("/app")
public class AppLoginController
{
    @Autowired
    private ILoginService loginService;

    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private INjtUserRegisterService userRegisterService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        System.out.println(loginBody.toString());
        // 创建小程序登录对象
        Login login = new Login();
        login.setUsername(loginBody.getUsername());
        login.setPassword(loginBody.getPassword());
        
        // 调用小程序专用登录服务
        LoginResult loginResult = loginService.login(login);
        
        if (loginResult.getSuccess()) {
            return AjaxResult.success(loginResult);
        } else {
            return AjaxResult.error(loginResult.getMessage());
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public AjaxResult logout()
    {
        loginService.logout("0");
        return AjaxResult.success("退出成功");
    }

    /**
     * 注册方法
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody NjtUserRegister user)
    {
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? AjaxResult.success("注册成功") : AjaxResult.error(msg);
    }

    /**
     * 获取用户信息
     */
    @PostMapping("/user/me")
    public AjaxResult getUserInfo()
    {
        return AjaxResult.success(loginService.getUserInfo());
    }
}